package com.mvc.web.user.controller;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mvc.web.common.base.BaseController;
import com.mvc.web.common.base.NotNeedCheckCookies;
import com.mvc.web.common.statics.Route;
import com.mvc.web.common.utils.AESUtil;
import com.mvc.web.common.utils.OSSManageUtil;
import com.mvc.web.common.utils.SMSUtil;
import com.mvc.web.common.utils.ToolsUtils;
import com.mvc.web.user.controller.validator.LoginValidator;
import com.mvc.web.user.service.UserService;
import com.mvc.web.user.vo.LoginForm;
import com.mvc.web.user.vo.UserVo;

/** 
 * @ClassName: UserController 
 * @Description: 登录控制器
 * @author: 白海安(baiha@jizhicar.com) 2017年8月25日 下午3:37:24
 * @version V1.0
 */
@Controller
public class UserController extends BaseController{
	
	@Autowired
	private LoginValidator loginValidator;
	@Autowired
	private UserService userService;
	
	/** 
	 * @Description: 用户登录，验证码或者密码两种方式 
	 * @author 白海安(baiha@jizhicar.com) 2017年8月28日 上午10:05:08
	 * @version V1.0
	 */
	@NotNeedCheckCookies
	@RequestMapping(value=Route.LOGIN,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String login(LoginForm vo,BindingResult validateResult,HttpServletResponse response){
		JSONObject res = new JSONObject();
		try {
			loginValidator.validate(vo, validateResult);
			if (validateResult.hasErrors()) {
				res.put("errorCode", validateResult.getAllErrors().get(0).getCode());
				res.put("errorMsg", validateResult.getAllErrors().get(0).getDefaultMessage());
				res.put("requestId", requestId);
				return res.toString();
			}
			vo.setCurrentTime(System.currentTimeMillis()/1000);
			UserVo user = userService.getUser(vo);
			if(user==null){
				res.put("errorCode", vo.getType()==1?1000:1001);
				res.put("errorMsg", vo.getType()==1?"请重新获取验证码":"手机号或密码错误");
				res.put("requestId", requestId);
				return res.toString();
			}
			Cookie cookie_uid = new Cookie("HYBBU",  AESUtil.base64AESEncrypt(user.getId()+""));
			cookie_uid.setPath("/");
			cookie_uid.setMaxAge(60*60*24*7);
			response.addCookie(cookie_uid);
			res.put("errorCode", 0);
	    	res.put("errorMsg", "success");
	    	res.put("requestId", requestId);
	    	res.put("data", JSONObject.toJSON(user));
			return res.toString();
		} catch (Exception e) {
			return Error("login error: ", e);
		}
	}
	/**   
	* @Description: 获取验证码
	* @author 白海安 （baihaian@126.com） 2016年6月13日 下午6:33:36
	* @version V1.0   
	*/
	@NotNeedCheckCookies
	@RequestMapping(value=Route.GET_CODE,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String getVeridyCode(String phone){
		JSONObject res = new JSONObject();
		try {
			if(ToolsUtils.isEmpty(phone)||ToolsUtils.ValidatePhone(phone)==false){
				res.put("errorCode", 1002);
				res.put("errorMsg", "请输入正确的手机号码");
				res.put("requestId", requestId);
				return res.toString();
			}
			//获取随机六位的数字验证码
			int verifyCode = getVerifyCode();
			String jsonData="{\"code\": "+verifyCode+",\"time\": 5}";
			SMSUtil.sendSms(jsonData, phone, "T170317001276");
			//如果该手机号不存在，添加注册，如果存在重置验证码，5分钟有效期时间
			userService.getVeridyCode(phone, verifyCode,(System.currentTimeMillis()+(5 * 60 * 1000))/1000);
			return Success();
		} catch (Exception e) {
			return Error("getVeridyCode error: ",e);
		}
	}
	
	public static int getVerifyCode() {
		String[] beforeShuffle = new String[] {"1","2", "3", "4", "5", "6", "7","8", "9" };
		List<String> list = Arrays.asList(beforeShuffle);
		Collections.shuffle(list);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
		}
		String afterShuffle = sb.toString();
		String result = afterShuffle.substring(3, 9);
		System.out.print(result);
		return Integer.parseInt(result);
	}
	/**   
	 * @Description: cookie校验失败
	 * @author 白海安 （baihaian@126.com） 2016年6月13日 下午6:33:36
	 * @version V1.0   
	 */
	@NotNeedCheckCookies
	@RequestMapping(value="/login/noCookie",produces="application/json; charset=utf-8")
	@ResponseBody
	public String noCookie(){
		JSONObject res = new JSONObject();
		res.put("errorCode", 800);
		res.put("errorMsg", "请登录系统");
		res.put("requestId", requestId);
		return res.toString();
	}
	/**   
	 * @Description: 无方法
	 * @author 白海安 （baihaian@126.com） 2016年6月29日 下午3:12:15
	 * @version V1.0   
	 */
	@NotNeedCheckCookies
	@RequestMapping(value="/login/noMethod",produces="application/json; charset=utf-8")
	@ResponseBody
	public String noMethod(){
		JSONObject res = new JSONObject();
		res.put("errorCode", 900);
		res.put("errorMsg", "无此接口");
		res.put("requestId", requestId);
		return res.toString();
	}
	/**   
	* @Description: 注销
	* @author 白海安 （baihaian@126.com） 2016年6月13日 下午6:58:02
	* @version V1.0   
	*/
	@NotNeedCheckCookies
	@ResponseBody
	@RequestMapping(value=Route.LOGOUT,produces="application/json; charset=utf-8")
	public String logout(HttpServletResponse response){
		Cookie cookie_cid = new Cookie("logininfo", "");
		cookie_cid.setPath("/");
		cookie_cid.setMaxAge(0);
		response.addCookie(cookie_cid);
		return Success();
	}
	
	/** 
	 * @Description: 用户头像上传 
	 * @author 白海安(baiha@jizhicar.com) 2017年8月28日 下午2:12:31
	 * @version V1.0
	 */
	@ResponseBody
	@RequestMapping(value=Route.USER_UPLOAD,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	public String upload(HttpServletRequest request,MultipartFile file){
		try {
			JSONObject res = new JSONObject();
			int uid = getIdFormCookie(request, "logininfo");
			if((file==null || file.isEmpty())){
				res.put("errorCode", 1002);
				res.put("errorMsg", "图片不能为空");
				res.put("requestId", requestId);
				return res.toString();
			}else if(file.getSize()>1024*1024*2){
				res.put("errorCode", 1002);
				res.put("errorMsg", "图片大小不能超过2M");
				res.put("requestId", requestId);
				return res.toString();
			}
			String imgUrl = upload(file);
			if (ToolsUtils.isEmpty(imgUrl)) {
				res.put("errorCode", 1003);
				res.put("errorMsg", "图片格式错误");
				res.put("requestId", requestId);
				return res.toString();
			}
			userService.uploadImage(uid,imgUrl);
	    	res.put("errorCode", 0);
	    	res.put("errorMsg", "success");
	    	res.put("requestId", requestId);
	    	UserVo vo = new UserVo();
	    	vo.setImgUrl(imgUrl);
	    	res.put("data", JSON.toJSON(vo));
	    	return res.toString();
		} catch (Exception e) {
			return Error("user upload error: ", e);
		}
	}
	
	private String upload(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String fileId = UUID.randomUUID().toString();
        int index = originalFilename.lastIndexOf(".");
        String imgExt = "jpg|jpeg|png|bmp|gif";
		String suffix = originalFilename.substring(index+1);
		//校验文件格式
		if (imgExt.indexOf(suffix.toLowerCase()) < 0) {
			return "";
		}
        fileId += "."+suffix;
        return OSSManageUtil.uploadFile(file.getInputStream(),fileId);
    }
	/** 
	 * @Description: 设置密码 
	 * @author 白海安(baiha@jizhicar.com) 2017年8月28日 下午3:28:45
	 * @version V1.0
	 */
	@RequestMapping(value=Route.USER_SETPWD,produces="application/json; charset=utf-8",method=RequestMethod.POST)
	@ResponseBody
	public String setPwd(HttpServletRequest request,String newPwd,String confirmPwd){
		try {
			JSONObject res = new JSONObject();
			if(ToolsUtils.isEmpty(newPwd)||ToolsUtils.isEmpty(confirmPwd)){
				res.put("errorCode", 1002);
		    	res.put("errorMsg", "新密码或确认密码不能为空");
		    	res.put("requestId", requestId);
		    	return res.toString();
			}else if(newPwd.equals(confirmPwd)==false){
				res.put("errorCode", 1002);
		    	res.put("errorMsg", "新密码或确认密码不一致");
		    	res.put("requestId", requestId);
		    	return res.toString();
			}
			int uid = getIdFormCookie(request, "logininfo");
			userService.setPwd(uid,newPwd);
			return Success();
		} catch (Exception e) {
			return Error("setPwd error: ", e);
		}
	}
}
